//
//  TwRequest.m
//  TuiTe
//
//  Created by 张 霄鹤 on 10-3-12.
//  Copyright 2010 xhzhang. All rights reserved.
//

#import "TwRequest.h"

#import "Constants.h"

#import "DataOutputStream.h"


@implementation TwRequest

@synthesize category;
@synthesize method;
@synthesize httpMethod;
@synthesize format;
@synthesize authType;
@synthesize hasID;
@synthesize authData;

- (id)init{
	if(self = [super init]){
		category = 0;
		method = 0;
		httpMethod = HTTP_API_GET;
		authType = AUTH_TYPE_NONE;
		hasID = 0;
		format = FORMAT_TYPE_XML;
		params = [[NSMutableDictionary alloc] init];
		oaparams = [[NSMutableDictionary alloc] init];
	}
	return self;
}

- (void)putParam:(id)value forKey:(NSString *)key{
	if(value && key){
		[params setObject:value forKey:key]; 
	}
}

- (void)putOAuthParam:(id)value forKey:(NSString *)key{
	if(value && key){
		[oaparams setObject:value forKey:key]; 
	}
}

- (void)putParams:(NSDictionary *)ps{
	if(ps){
		if([ps count] > 0){
			[params addEntriesFromDictionary:ps];
		}
	}
}

- (NSData *)getRequestData{
	NSData *ret = nil;
	DataOutputStream *dout = [[DataOutputStream alloc] init];
	NSInteger iv = ((category & 0x0ff) << 4) | (method & 0x0ff);
	[dout write:iv];
	// iv = ((httpMethod & 0x03) << 6) | ((authType & 0x03) << 4) | ((format & 0x03) << 2) | (hasID & 0x03);
	iv = ((httpMethod & 0x0f) << 4) | ((authType & 0x0f));
	[dout write:iv];
	iv = ((format & 0x0f) << 4) | (hasID & 0x0f);
	[dout write:iv];
	NSInteger len = [params count];
	iv = (len & 0x0ff);
	[dout write:iv];
	
	if(iv > 0){
		for(id key in params){
			id value = [params objectForKey:key];
			[dout writeUTF:(NSString *)key];
			[dout writeUTF:(NSString *)value];
		}
	}
	
	if(authType == AUTH_TYPE_BASIC){
		if(authData){
			iv = [authData length];
			[dout writeShort:iv];
			[dout writeBytes:authData];
		}else{
			[dout writeShort:0];
		}
	}else if (authType == AUTH_TYPE_OAUTH) {
		NSInteger cn = [oaparams count];
		[dout writeShort:cn];
		if (cn > 0) {
			for (id key in oaparams) {
				[dout writeUTF:(NSString *)key];
				[dout writeUTF:(NSString *)[oaparams objectForKey:key]];
			}
		}
	}
	
	ret = [[dout toByteArray] retain];
	[dout release];
	return ret;
}

- (void)dealloc{
	[params release];
	if(authData){
		[authData release];
	}
	[super dealloc];
}

@end
